import { ref } from 'vue'
import axios from 'axios'

// 类型定义
export interface FileInfo {
  type: string
  name: string
  size: number
  local: string
  extName: string
}

export interface FileTypeFilter {
  name: string
  ext: string[]
}

export interface SelectFileOptions {
  multiple?: boolean
  fileTypes?: FileTypeFilter[]
  title?: string
  initialDir?: string
}

export interface FileSelectorResult {
  files: FileInfo[]
  cancelled: boolean
}

export interface ApiResponse {
  success: boolean
  data?: FileSelectorResult
  platform?: string
  error?: string
}

/**
 * Vue3 文件选择器 Hook
 */
export function useFileSelector(baseUrl: string = 'http://localhost:5001') {
  const loading = ref(false)

  /**
   * 选择文件
   * @param options 文件选择选项
   */
  const selectFile = async (options: SelectFileOptions = {}): Promise<FileInfo[]> => {
    loading.value = true

    try {
      const requestData = {
        multiple: options.multiple || false,
        file_types: options.fileTypes || null,
        title: options.title || '选择文件',
        initial_dir: options.initialDir || null
      }

      const response = await axios.post<ApiResponse>(`${baseUrl}/api/file-selector`, requestData, {
        headers: {
          'Content-Type': 'application/json'
        }
      })

      if (!response.data.success) {
        throw new Error(response.data.error || '文件选择失败')
      }

      const result = response.data.data || { files: [], cancelled: true }
      return result.files

    } catch (err: any) {
      console.error('文件选择器错误:', err)
      return []
    } finally {
      loading.value = false
    }
  }

  return {
    loading,
    selectFile
  }
}

export default useFileSelector 